package main

import (
	"fmt"
	"log"
	"net"
)

var html = `<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>magedu</title>
</head>
<body>
	<h1>马哥教育www.magedu.com -- Goroutine</h1>
</body>
</html>`

var head = `HTTP/1.1 200 OK
Date: Mon, 24 Oct 2022 20:04:23 GMT
Content-Type: text/html
Content-Length: %d
Connection: keep-alive
Server: wayne.magedu.com
%s`

var response = fmt.Sprintf(head, len(html), html)

func main() {
	laddr, err := net.ResolveTCPAddr("tcp4", "0.0.0.0:9999")
	if err != nil {
		log.Panicln(err)
	}
	server, err := net.ListenTCP("tcp4", laddr)
	if err != nil {
		log.Panicln(err)
	}
	defer server.Close()

	for {
		conn, err := server.Accept()
		if err != nil {
			log.Panicln(err)
		}

		go func() {
			defer conn.Close()

			buffer := make([]byte, 4096)
			n, err := conn.Read(buffer)
			if n == 0 {
				log.Printf("客户端%s主动断开", conn.RemoteAddr().String())
				return
			}
			if err != nil {
				log.Println(err)
				return
			}
			conn.Write([]byte(response))
		}()
	}
}
